<template>
  <!-- 文件发布 -->
  <div class="filerelease">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >
      
        <!-- 左上方菜单栏 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.file_delete"
            @click="handleDelete">
            删 除
          </el-button>
        </template>

        <!-- 附件表单自定义 -->
        <template slot="fjForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="fjFileList"
              :before-upload="beforeUploadFJ"
              :on-remove="handleRemoveFJ"
              :on-success="uploadFJSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in fjFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

        <!-- 状态表格自定义 -->
        <template slot="status" slot-scope="scope">
          <span>{{formatStatus(scope.row)}}</span>
        </template>

        <!-- 附件表格自定义 -->
        <template slot="fj" slot-scope="scope">
          <div class="enclosure_div">
            <a :href="downloadHead + scope.row['fj']" v-if="scope.row['fj'] !== '' && scope.row['fj'] !== undefined">
              <i class="el-icon-download"></i>下载附件
            </a>
            <span v-else>-</span>
          </div>
        </template>

        <!-- 审批表格自定义 -->
        <template slot="approve" slot-scope="scope">
          <div>
            <el-button
              v-if="scope.row['auditPermissions']"
              type="success"
              size="mini"
              @click="handleExamine(scope.row)">
              审 核
            </el-button>
            <el-button
              v-if="scope.row['approvalPermissions']"
              type="warning"
              size="mini"
              @click="handleApprove(scope.row)">
              批 准
            </el-button>
            <span v-if="!scope.row['auditPermissions'] && !scope.row['approvalPermissions']">-</span>
          </div>
        </template>

      </avue-crud>

      <!-- 审核、批准弹窗 -->
      <el-dialog 
        :title="dialogTitle"
        append-to-body
        :visible.sync="updateDialog"
        :close-on-click-modal="false" 
        :before-close="closeUpdateDialog"
        width="60%"
        class="examine_approve_dialog"
      > 

        <!-- 内容 -->
        <avue-form 
          ref="updateForm" 
          v-model="updateObj" 
          :option="updateOption" 
          @submit="confirmExamineOrApprove"
        >

          <!-- 评审附件表单自定义 -->
          <template slot="fj">
            <div>
              <span v-if="psfjFileList === undefined || psfjFileList.length === 0">-</span>

              <a 
                v-else 
                v-for="(item, index) in psfjFileList"
                :key="index"
                :href="downloadHead + item.response.data.id"
                style="color:#409EFF"
              >
                <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
              </a>
            </div>
          </template>

          <!-- 自定义按钮 -->
          <template slot="menuForm">
            <el-button 
              size="small"
              icon="el-icon-close"
              @click="closeUpdateDialog()">
              取 消
            </el-button>
          </template>
        </avue-form>

      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  add,
  update,
  remove,
  getStatusList,
  modifyStatus
} from "@/api/securitysystemmanagement/file";
import { mapGetters } from "vuex";
import { getDeptTree } from "@/api/system/dept";
import { getToken } from "@/util/auth";

export default {
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 200,
        addBtnText: "文件发布",
        column: [
          {
            label: "文件编号",
            prop: "wjbh",
            align: "center",
            width: 180,
            rules: [{
              required: true,
              message: "请输入文件编号",
              trigger: "blur"
            }]
          },
          {
            label: "文件名称",
            prop: "wjmc",
            align: "center",
            search: true,
            rules: [{
              required: true,
              message: "请输入文件名称",
              trigger: "blur"
            }]
          },
          {
            label: "类别",
            prop: "lb",
            align: "center",
            width: 80,
            search: true,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=safe_file_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            }
          },
          {
            label: "性质",
            prop: "xz",
            align: "center",
            width: 60,
            search: true,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=safe_file_nature",
            props: {
              label: "dictValue",
              value: "dictKey",
            }
          },
          {
            label: "发布日期",
            prop: "createTime",
            width: 100,
            display: false,
            align: "center",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd"
          },
          {
            label: "发布人",
            prop: "fbrName",
            display: false,
            align: "center",
            width: 100
          },
          {
            label: "发送部门",
            prop: "fsbm",
            hide: true,
            span: 24,
            type: "tree",
            multiple: true,
            checkStrictly: true,
            dicData: [],
            props: {
              label: "title"
            },
            rules: [{
              required: true,
              message: "请选择发送部门",
              trigger: "blur"
            }]
          },
          {
            label: "文件内容",
            prop: "wjnr",
            hide: true,
            type: "textarea",
            span: 24,
            maxlength: 150
          },
          {
            label: "审核人",
            prop: "shren",
            hide: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择审核人",
              trigger: "change"
            }]
          },
          {
            label: "批准人",
            prop: "spren",
            hide: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择批准人",
              trigger: "change"
            }]
          },
          {
            label: "附件",
            prop: "fj",
            align: "center",
            width: 100,
            span: 24,
            slot: true,
            formslot: true
          },
          {
            label: "状态",
            display: false,
            prop: "status",
            align: "center",
            width: 100,
            slot: true
          },
          {
            label: "审批",
            display: false,
            prop: "approve",
            align: "center",
            width: 100,
            slot: true
          }
        ]
      },
      // 附件
      dialogType: "",
      downloadHead: "/api/fileManager/download/",
      SetHeaders: { "Blade-Auth": getToken() },
      fjFileList: [],
      statusObj: {},
      // 审核、批准弹窗
      updateDialogType: "",
      examineStr: "EXAMINE",
      approveStr: "APPROVE",
      dialogTitle: "",
      updateDialog: false,
      updateObj: {},
      psfjFileList: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.file_add, false),
        viewBtn: this.vaildData(this.permission.file_view, false),
        delBtn: this.vaildData(this.permission.file_delete, false),
        editBtn: this.vaildData(this.permission.file_edit, false)
      };
    },

    // 勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },

    updateOption() {
      return {
        size: "small",
        submitText: "确 定",
        mockBtn: false,
        printBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "文件编号",
            prop: "wjbh",
            disabled: true,
            rules: [{
              required: true,
              message: "请输入文件编号",
              trigger: "blur"
            }]
          },
          {
            label: "文件名称",
            prop: "wjmc",
            disabled: true,
            rules: [{
              required: true,
              message: "请输入文件名称",
              trigger: "blur"
            }]
          },
          {
            label: "类别",
            prop: "lb",
            disabled: true,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=safe_file_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            }
          },
          {
            label: "性质",
            prop: "xz",
            disabled: true,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=safe_file_nature",
            props: {
              label: "dictValue",
              value: "dictKey",
            }
          },
          {
            label: "发送部门",
            prop: "fsbm",
            disabled: true,
            span: 24,
            type: "tree",
            multiple: true,
            checkStrictly: true,
            dicData: [],
            props: {
              label: "title"
            },
            rules: [{
              required: true,
              message: "请选择发送部门",
              trigger: "blur"
            }]
          },
          {
            label: "文件内容",
            prop: "wjnr",
            disabled: true,
            type: "textarea",
            span: 24,
            maxlength: 150
          },
          {
            label: "审核人",
            prop: "shren",
            disabled: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择审核人",
              trigger: "change"
            }]
          },
          {
            label: "批准人",
            prop: "spren",
            disabled: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择批准人",
              trigger: "change"
            }]
          },
          {
            label: "附件",
            prop: "fj",
            span: 24,
            slot: true,
            formslot: true
          },
          {
            label: "部门审核",
            prop: "deptExamine",
            disabled: true,
            type: "radio",
            display: false,
            dicData: [{
              label: "同意",
              value: 1
            }, {
              label: "不同意",
              value: 2
            }],
            rules: [{
              required: true,
              message: "请选择部门审核意见",
              trigger: "change"
            }]
          },
          {
            label: "领导批准",
            prop: "leaderApprove",
            disabled: true,
            type: "radio",
            display: false,
            dicData: [{
              label: "同意",
              value: 1
            }, {
              label: "不同意",
              value: 2
            }],
            rules: [{
              required: true,
              message: "请选择领导批准意见",
              trigger: "change"
            }]
          }
        ]
      }
    }
  },
  mounted() {
    this.initData();
  },
  methods: {

    // 初始化页面
    initData() {
      var tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;
      getDeptTree(tenantId).then(res => {
        const fsbmColumn = this.findObject(this.option.column, "fsbm");
        fsbmColumn.dicData = res.data.data;
      }).then(() => {
        getStatusList().then(res => {
          this.statusObj = {};
          res.data.data.forEach(item => {
            this.statusObj[item.dictKey] = item.dictValue;
          });
        }).then(() => {
          this.onLoad(this.page);
        });
      });
    },

    // 格式化状态列
    formatStatus(row) {
      var zt = row.zt;
      return this.statusObj[zt];
    },

    // 新增
    rowSave(row, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.fsbm = row.fsbm.join(",");
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.fsbm = typeof row.fsbm === "object" ? row.fsbm.join(",") : row.fsbm;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开新增、修改、查看弹窗前
    beforeOpen(done, type) {
      if(type === "edit") {
        if(!this.form.editPermissions) {
          this.$message.warning("当前文件信息不可编辑!");
          return;
        }
      }
      this.dialogType = type;
      this.fjFileList = [];
      if (["edit", "view"].includes(type)) {
        if (this.form.fj && this.form.bladeFiles && JSON.stringify(this.form.bladeFiles) !== "{}") {
          this.fjFileList.push({
            name: this.form.bladeFiles.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: this.form.bladeFiles
            }
          });
        }
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 上传附件
     */

    // 上传附件前
    beforeUploadFJ(file) {
      console.log(file);
      var isLimit = this.fjFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个附件!");
      }
      return isLimit;
    },

    // 上传附件成功
    uploadFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.fjFileList = fileList;
      this.form.fj = response.data.id;
    },

    // 删除附件
    handleRemoveFJ(file, fileList) {
      this.fjFileList = fileList;
      this.form.fj = "";
    },

    /**
     * 审核、批准弹窗
    */

    // 格式化审核、批准弹窗表单数据
    formatUpdateForm(row) {
      var data = {};
      for(var key in row) {
        data[key] = row[key];
      }
      return data;
    },

    // 获取部门审核、领导批准字段值
    formatExamineApproveValue(obj) {
      if(obj.zt === 0) {
        obj["deptExamine"] = "";
        obj["leaderApprove"] = "";
      } else if(obj.zt === 1) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = "";
      } else if(obj.zt === 2) {
        obj["deptExamine"] = 2;
        obj["leaderApprove"] = "";
      } else if(obj.zt === 3) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = 1;
      } else if(obj.zt === 4) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = 2;
      } else {
        obj["deptExamine"] = "";
        obj["leaderApprove"] = "";
      }
    },

    // 打开审核弹窗
    handleExamine(row) {
      this.updateDialogType = this.examineStr;
      this.updateDialog = true;
      this.dialogTitle = "审核文件";
      this.updateObj = this.formatUpdateForm(row);
      this.psfjFileList = [];
      if (row.fj && row.bladeFiles && JSON.stringify(row.bladeFiles) !== "{}") {
        this.psfjFileList.push({
          name: row.bladeFiles.fileName,
          response: {
            code: 200,
            msg: "操作成功",
            success: true,
            data: row.bladeFiles
          }
        });
      }
      this.updateOption.column.forEach(item => {
        if(item.prop === "deptExamine") {
          item.display = true;
          item.disabled = false;
        }
        if(item.prop === "leaderApprove") {
          item.display = false;
          item.disabled = true;
        }
      });
      this.formatExamineApproveValue(this.updateObj);
    },

    // 打开批准弹窗
    handleApprove(row) {
      this.updateDialogType = this.approveStr;
      this.updateDialog = true;
      this.dialogTitle = "批准文件";
      this.updateObj = this.formatUpdateForm(row);
      this.psfjFileList = [];
      if (row.fj && row.bladeFiles && JSON.stringify(row.bladeFiles) !== "{}") {
        this.psfjFileList.push({
          name: row.bladeFiles.fileName,
          response: {
            code: 200,
            msg: "操作成功",
            success: true,
            data: row.bladeFiles
          }
        });
      }
      this.updateOption.column.forEach(item => {
        if(item.prop === "deptExamine") {
          item.display = true;
          item.disabled = true;
        }
        if(item.prop === "leaderApprove") {
          item.display = true;
          item.disabled = false;
        }
      });
      this.formatExamineApproveValue(this.updateObj);
    },

    // 关闭、取消审核&批准&修订弹窗
    closeUpdateDialog() {
      this.updateObj = {};
      this.updateDialogType = "";
      this.updateDialog = false;
      this.dialogTitle = "";
    },

    // 确定审核、批准
    confirmExamineOrApprove() {
      if(this.updateDialogType === this.examineStr) {
        this.confirmExamine();
      } else if(this.updateDialogType === this.approveStr) {
        this.confirmApprove();
      }
    },

    // 确认审核
    confirmExamine() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          modifyStatus(this.updateObj.id, this.updateObj.zt, this.updateObj.deptExamine).then(res => {
            if(res.data.success) {
              done();
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
        }
      })
    },

    // 确认批准
    confirmApprove() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          modifyStatus(this.updateObj.id, this.updateObj.zt, this.updateObj.leaderApprove).then(res => {
            if(res.data.success) {
              done();
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
        }
      })
    }

  }
};
</script>

<style lang="scss" scpoed>
.filerelease {
  .enclosure_div {
    a {
      font-size: 12px;
      color: #409eff;

      i {
        margin-right: 5px;
      }
    }
  }
}

.examine_approve_dialog {
  .avue-form__menu--center {
    text-align: center;
  }
}
</style>